// ***********************************************
// This example commands.js shows you how to
// create various custom commands and overwrite
// existing commands.
//
// For more comprehensive examples of custom
// commands please read more here:
// https://on.cypress.io/custom-commands
// ***********************************************
//
//
// -- This is a parent command --
// Cypress.Commands.add('login', (email, password) => { ... })
//
//
// -- This is a child command --
// Cypress.Commands.add('drag', { prevSubject: 'element'}, (subject, options) => { ... })
//
//
// -- This is a dual command --
// Cypress.Commands.add('dismiss', { prevSubject: 'optional'}, (subject, options) => { ... })
//
//
// -- This will overwrite an existing command --
// Cypress.Commands.overwrite('visit', (originalFn, url, options) => { ... })

// 增强的登录命令，支持不同角色和错误处理
Cypress.Commands.add('login', (username, password, options = {}) => {
  const { role = 'Student', expectSuccess = true, timeout = 10000 } = options
  
  cy.visit('/login')
  cy.get('[data-cy=account-input]').type(username)
  cy.get('[data-cy=password-input]').type(password)
  cy.get('[data-cy=login-button]').click()
  
  if (expectSuccess) {
    cy.url({ timeout }).should('include', '/mainPage')
    
    // 如果指定了角色，自动切换到该角色
    if (role !== 'Student') {
      cy.get('.role-nav .btn').contains(`我是${role === 'Teacher' ? '老师' : '学生'}`).click()
      cy.wait(1000)
    }
  }
})

// 登录为教师
Cypress.Commands.add('loginAsTeacher', (username = 'teacher001', password = 'teacher123') => {
  cy.login(username, password, { role: 'Teacher' })
})

// 登录为学生
Cypress.Commands.add('loginAsStudent', (username = 'student001', password = 'student123') => {
  cy.login(username, password, { role: 'Student' })
})

// 增强的课程创建命令
Cypress.Commands.add('createCourse', (courseData = {}) => {
  const defaultData = {
    courseId: `TEST_${Date.now()}`,
    courseName: '测试课程',
    description: '这是一个测试课程',
    teachingGoal: '测试教学目标',
    examinationMethod: '测试考核方法',
    credits: '3'
  }
  
  const data = { ...defaultData, ...courseData }
  
  cy.get('.create-btn, [data-cy=create-course-btn]').click()
  cy.url().should('include', '/create-course')
  
  // 填写课程信息
  cy.get('[data-cy=course-id-input], input[name="courseId"]').type(data.courseId)
  cy.get('[data-cy=course-name-input], input[name="courseName"]').type(data.courseName)
  cy.get('[data-cy=course-description], textarea[name="description"]').type(data.description)
  cy.get('[data-cy=teaching-goal], textarea[name="teachingGoal"]').type(data.teachingGoal)
  cy.get('[data-cy=examination-method], textarea[name="examinationMethod"]').type(data.examinationMethod)
  cy.get('[data-cy=credits-input], input[name="credits"]').type(data.credits)
  
  cy.get('[data-cy=submit-course], .submit-btn').click()
  cy.wait(3000)
  
  // 返回课程数据供后续使用
  cy.wrap(data).as('createdCourse')
})

// 加入课程命令
Cypress.Commands.add('joinCourse', (courseId) => {
  cy.get('.join-btn, [data-cy=join-course-btn]').click()
  cy.url().should('include', '/join-course')
  
  cy.get('[data-cy=course-id-input], input[name="courseId"]').type(courseId)
  cy.get('[data-cy=join-submit], .join-submit-btn').click()
  cy.wait(2000)
})

// 进入课程
Cypress.Commands.add('enterCourse', (courseIndex = 0) => {
  cy.get('.course-card').eq(courseIndex).find('.enter-btn').click()
  cy.wait(2000)
})

// 导航到课程模块
Cypress.Commands.add('navigateToModule', (moduleName) => {
  cy.contains(moduleName).click()
  cy.wait(1000)
})

// API请求命令
Cypress.Commands.add('apiRequest', (method, endpoint, options = {}) => {
  const { body, headers = {}, failOnStatusCode = false } = options
  
  const defaultHeaders = {
    'Content-Type': 'application/json',
    'Authorization': 'Bearer test-token',
    ...headers
  }
  
  return cy.request({
    method,
    url: `http://localhost:8080${endpoint}`,
    body,
    headers: defaultHeaders,
    failOnStatusCode
  })
})

// 等待API响应
Cypress.Commands.add('waitForApi', (alias, timeout = 10000) => {
  cy.wait(alias, { timeout })
})

// 检查元素是否存在
Cypress.Commands.add('elementExists', (selector) => {
  cy.get('body').then($body => {
    return $body.find(selector).length > 0
  })
})

// 条件点击
Cypress.Commands.add('clickIfExists', (selector) => {
  cy.get('body').then($body => {
    if ($body.find(selector).length > 0) {
      cy.get(selector).click()
    }
  })
})

// 清理测试数据
Cypress.Commands.add('cleanup', () => {
  // 清理localStorage
  cy.clearLocalStorage()
  
  // 清理cookies
  cy.clearCookies()
  
  // 清理sessionStorage
  cy.window().then((win) => {
    win.sessionStorage.clear()
  })
})

// 模拟文件上传
Cypress.Commands.add('uploadFile', (selector, fileName, fileType = 'application/pdf') => {
  cy.get(selector).then(input => {
    const file = new File(['test content'], fileName, { type: fileType })
    const dataTransfer = new DataTransfer()
    dataTransfer.items.add(file)
    input[0].files = dataTransfer.files
    cy.wrap(input).trigger('change', { force: true })
  })
})

// 验证成功消息
Cypress.Commands.add('verifySuccessMessage', (message = '操作成功') => {
  cy.get('body').then($body => {
    if ($body.find('.success-message, .alert-success').length > 0) {
      cy.get('.success-message, .alert-success').should('contain', message)
    } else {
      cy.log(`预期成功消息: ${message}`)
    }
  })
})

// 验证错误消息
Cypress.Commands.add('verifyErrorMessage', (message = '操作失败') => {
  cy.get('body').then($body => {
    if ($body.find('.error-message, .alert-error, .alert-danger').length > 0) {
      cy.get('.error-message, .alert-error, .alert-danger').should('contain', message)
    } else {
      cy.log(`预期错误消息: ${message}`)
    }
  })
})